//
//  YBMineInviteVC.swift
//  Moonlight
//
//  Created by 清风徐来 on 2023/7/5.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import EachNavigationBar
import Photos
import HandyJSON
import SwiftyJSON
import SDWebImage

class YBMineInviteVC: BaseVC {
    
    // MARK: - lazy
    lazy var vm: YBMineViewModel = {
        let vm = YBMineViewModel()
        return vm
    }()
    
    private lazy var contentView: UIView = {
        let iv = UIView()
        return iv
    }()
    
    private lazy var bgImgView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        return iv
    }()
    
    private lazy var codeImgView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        return iv
    }()
    
    private lazy var saveBtn: UIButton = {
        let btn = self.bk_addButton(title: "保存海报", bgColor: .clear, titleColor: .white)
        btn.isUserInteractionEnabled = true
        btn.bk_addTarget { [self] button in
            self.savePicAction()
        }
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigation.item.title = "邀请有奖"
        view.backgroundColor = UIColor.hex("#020202")
        
        view.addSubview(contentView)
        contentView.addSubviews([bgImgView])
        bgImgView.addSubview(codeImgView)
        view.addSubview(saveBtn)
        
        contentView.snp.makeConstraints { make in
            make.width.equalTo(kScreenWidth - 40)
            make.top.equalTo(kNavigationBarHeight + 20)
            make.centerX.equalToSuperview()
        }
        
        // 750 * 1340
        bgImgView.snp.makeConstraints { make in
            make.top.left.centerX.equalToSuperview()
            make.height.equalTo(bgImgView.snp.width).multipliedBy(1.78666)
            make.bottom.equalToSuperview()
        }
        
        codeImgView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(((kScreenWidth - 40) * 1340 / 750) * 0.46716)
            make.width.height.equalTo(bgImgView.snp.width).multipliedBy(0.31066)
        }
        
        saveBtn.snp.makeConstraints { make in
            make.top.equalTo(contentView.snp.bottom).offset(30)
            make.centerX.equalToSuperview()
            make.left.equalTo(10)
            make.height.equalTo(40)
        }
        
        // 请求海报图片
        requestPostCardInfo()
    }
    
    //MARK: - 请求海报数据
    func requestPostCardInfo() {
        vm.req_QrCode { ok, obj, msg, code in
            if ok {
                let js = obj as? JSON
                let code = js?[NetDataKey]["code"].stringValue
                if let imageData = Data(base64Encoded: code ?? "", options: .ignoreUnknownCharacters) {
                    // 这里的base64String是您的Base64字符串
                    // 继续处理图片数据
                    if let image = UIImage(data: imageData) {
                        // 成功将Data转换为UIImage
                        // 可以使用image对象进行进一步的操作
                        self.codeImgView.image = image
                    } else {
                        // 无法将Data转换为UIImage
                        // 处理转换失败的情况
                        // 失败的
                        print("图片处理失败")
                    }

                }
            }
        }
        
        vm.req_QrBanner { ok, obj, msg, code in
            if ok {
                let js = obj as? JSON
                let pic = js?[NetDataKey]["pic"].stringValue
                self.bgImgView.sd_setImage(with: URL(string: pic))
            }
        }
    }
}


//MARK: - ACTION
extension YBMineInviteVC {
    
    // 保存操作
    func savePicAction() {
        let img = contentView.bk_generateFrameScreenshot()
        self.saveImageToPhotoLibrary(image: img) { success, error in
            if success {
                HintTool.toast("保存成功")
            } else {
                HintTool.toast("保存失败")
            }
        }
    }
    
    // 检查相册权限
    func checkPhotoLibraryAuthorizationStatus(completion: @escaping (Bool) -> Void) {
        let status = PHPhotoLibrary.authorizationStatus()
        switch status {
        case .authorized:
            completion(true)
        case .denied, .restricted:
            completion(false)
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { status in
                completion(status == .authorized)
            }
        case .limited:
            completion(false)
        @unknown default:
            completion(false)
        }
    }
    
    // 保存图片
    func saveImageToPhotoLibrary(image: UIImage, completion: ((Bool, Error?) -> Void)? = nil) {
        checkPhotoLibraryAuthorizationStatus { authorized in
            if authorized {
                PHPhotoLibrary.shared().performChanges {
                    PHAssetChangeRequest.creationRequestForAsset(from: image)
                } completionHandler: { success, error in
                    DispatchQueue.main.async {
                        completion?(success, error)
                    }
                }
            } else {
                completion?(false, nil)
            }
        }
    }
    
}
